var express = require('express');
var router = express.Router();
var async = require('async');
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = "mongodb://localhost:27017/douban";

router.get('/',function(req,res,next){
  var item = req.query.item;

	// 构建分页基本信息
	var pageNo = req.query.pageNo,
		pageNo = pageNo?pageNo:1,
		pageSize = 5,
		count = 0,
		totalPages = 0;


	var findData = function(db,callback){
        //连接表
        var conn = db.collection(item);
		//串行无关联
		async.parallel([
			function(callback){
				conn.find({}).toArray(function(err,results){
					if(err){
						console.log(err);
					}else {
						totalPages = Math.ceil(results.length/pageSize);
						count = results.length;
						callback(null,'');
					}
				});
			},
			function(callback){

				conn.find({}).sort({_id:-1}).skip((pageNo-1)*pageSize).limit(pageSize).toArray(function(err,results){
					if(err){
						console.log(err);
					}else {
						callback(null,results);
					}
				});

			}
		],function(err,results){
			 callback(results[1]);


		});

    };

    MongoClient.connect(DB_CONN_STR,function(err,db){
        if(err){
            console.log(err);
        }else{
            console.log('connect success');
            findData(db,function(results){
               console.log(results);
				res.render('items',{
					pageNo:pageNo,
					totalPages:totalPages,
					list:results,
					count:count,
          item:item
				});
                db.close();
            });
        }
    });

});

module.exports = router;